package com.zl.gmadmin.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zl.gmadmin.common.ApiResponse;
import com.zl.gmadmin.common.Status;
import com.zl.gmadmin.entity.SysUser;
import com.zl.gmadmin.exception.BaseException;
import com.zl.gmadmin.exception.UserException;
import com.zl.gmadmin.payload.UserPassword;
import com.zl.gmadmin.payload.UserQueryCriteria;
import com.zl.gmadmin.service.SysUserService;
import com.zl.gmadmin.utils.LogUtil;
import com.zl.gmadmin.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author zhangliang
 * @version 1.0
 * @date 2021/3/4 14:05
 */
@RestController
@Api(tags = "系统: 用户管理")
@RequestMapping("/api/system/users")
public class SysUserController {

    private final SysUserService sysUserService;

    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    public SysUserController(SysUserService sysUserService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.sysUserService = sysUserService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @GetMapping
    @ApiOperation("查询用户")
    public ApiResponse queryUsers(UserQueryCriteria queryCriteria, Page<SysUser> page) {
        return ApiResponse.ofStatus(Status.SUCCESS, sysUserService.selectPageVo(queryCriteria, page));
    }

    @ApiOperation("根据id获取用户信息")
    @GetMapping("/{id}")
    public ApiResponse getUserById(@PathVariable(value = "id") Long id) {
        SysUser sysUser = sysUserService.getById(id);
        sysUser.setPassword(null);
        return ApiResponse.ofSuccess(sysUser);
    }

    @PostMapping
    @ApiOperation("添加用户")
    public ApiResponse addUser(@RequestBody @Validated SysUser user) {
        user.setCreateBy(SecurityUtils.getCurrentUser().getUsername());
        user.setPassword(bCryptPasswordEncoder.encode("123456"));
        Object o = sysUserService.insert(user, user.getRoles(), user.getJobs());

        return ApiResponse.ofSuccess(o);
    }

    @DeleteMapping
    @ApiOperation("批量删除用户")
    public ApiResponse delUser(@RequestBody List<Long> ids) {
        sysUserService.delUsers(ids);
        return ApiResponse.ofSuccess();
    }

    @PutMapping
    @ApiOperation("修改用户信息")
    public ApiResponse updateUser(@RequestBody SysUser sysUser) {
        sysUserService.updateUserById(sysUser, sysUser.getRoles(), sysUser.getJobs());

        return ApiResponse.ofMessage("修改用户信息成功");
    }


    @ApiOperation("导出用户信息")
    @GetMapping("/download")
    public void download(UserQueryCriteria criteria, HttpServletResponse response) throws IOException {

        LogUtil.debug("导出:" + JSONUtil.toJsonStr(criteria));
        sysUserService.download(response, criteria.getIds());
    }

    @ApiOperation("修改用户密码")
    @PutMapping("/{id}")
    public void updateUserPasswordById(@PathVariable(value = "id") Long id, @RequestBody UserPassword userPassword) {
        SysUser sysUser = sysUserService.getById(id);
        LogUtil.debug(JSONUtil.toJsonStr(sysUser));
        if (sysUser.getPassword() == bCryptPasswordEncoder.encode(userPassword.getNewPassword())) {
            throw new BaseException("新密码与旧密码一致");
        } else {
            if (bCryptPasswordEncoder.matches(userPassword.getOldPassword(), sysUser.getPassword())){
                sysUser.setPassword(bCryptPasswordEncoder.encode(userPassword.getNewPassword()));
                sysUserService.updateById(sysUser);
                throw  new UserException(Status.UPDATE_PASSWORD_SUCCESS);
            }else {
                throw  new UserException(Status.OLD_PASSWORD);
            }
        }
    }
}
